// Copyright 2010 Alexandre Tristan St-Cyr <tristan.stcyr@gmail.com>

package com.codeplex.loadjava;

import java.io.IOException;
import java.io.InputStream;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.objectweb.asm.ClassReader;


public class JavaModelReader {
	
	private static Logger logger = Logger.getLogger(JavaModelReader.class.getCanonicalName());
	
	private String classpath;

	public JavaModelReader(String classpath) {
		this.classpath = classpath;
	}
	
	public void accept(final IJavaModelVisitor visitor) {
		ClassPathReader classpathReader = new ClassPathReader(classpath);
		classpathReader.accept(new IClassPathVisitor() {

			@Override
			public void visit(InputStream classfile, String relativeName) throws IOException {
				visitor.visitClassFile(relativeName);
				ClassReader classReader = new ClassReader(classfile);
				JavaModelClassAdapter classVisitor = 
					new JavaModelClassAdapter(visitor, getPackageName(relativeName));
				classReader.accept(classVisitor, 0);
				visitor.endVisitClassFile(relativeName);
			}

			@Override
			public void onError(IOException e) {
				logger.log(Level.WARNING, e.getMessage(), e);
			}
		});
	}
	
	private String getPackageName(String relativeName) {
		int slashIndex = relativeName.lastIndexOf("/");
		if (slashIndex < 0)
			return "";
		return relativeName.substring(0, relativeName.lastIndexOf("/")).replace('/', '.');
	}
}
